<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="120px" label-position="left">
          <!--         <el-form-item label="健身房id" prop="gymId">
            <el-input v-model="queryParams.gymId" placeholder="请输入健身房id" clearable style="width: 220px"
              @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="退票规则名称" prop="refundRuleName">
            <el-input v-model="queryParams.refundRuleName" placeholder="请输入退票规则名称" clearable style="width: 220px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="是否过期退款" prop="allowExpiredRefund">
            <el-select v-model="queryParams.allowExpiredRefund" placeholder="请选择是否过期退款" style="width: 240px">
              <el-option v-for="item in dataoo.options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="手续费类型" prop="refundFeeMode">
            <el-input v-model="queryParams.refundFeeMode" placeholder="1-无手续费；2-每张票需要手续费；3-按销售价格百分比收取"
              clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="退款手续费" prop="refundFee">
            <el-input v-model="queryParams.refundFee" placeholder="请输入退款手续费" clearable style="width: 220px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <!--        <el-form-item label="是否需要退款审核" prop="needCheck">
            <el-input v-model="queryParams.needCheck" placeholder="请输入是否需要退款审核；0-不需要；1-需要，默认0" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['primary:gymRefundRule:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['primary:gymRefundRule:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['primary:gymRefundRule:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['primary:gymRefundRule:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="gymRefundRuleList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" prop="id" v-if="true" />
        <!-- <el-table-column label="健身房id" align="center" prop="gymId" /> -->
        <el-table-column label="退票规则名称" align="center" prop="refundRuleName" />
        <el-table-column label="退款类型" align="center">
          <template #default="scope">
            <dict-tag :options="g_refund_type" :value="scope.row.refundType" />
          </template>
        </el-table-column>
        <el-table-column label="允许过期退款" align="center" prop="allowExpiredRefund">
          <template v-slot="{ row }">
            {{ row.allowExpiredRefund == 0 ? '不允许' : '允许' }}
          </template>
        </el-table-column>

        <el-table-column label="手续费类型" align="center">
          <template #default="scope">
            <dict-tag :options="g_refundfee_type" :value="scope.row.refundFeeMode" />
          </template>
        </el-table-column>
        <el-table-column label="退款手续费" align="center" prop="refundFee" />
        <el-table-column label="是否需要退款审核" align="center" prop="needCheck">
          <template v-slot="{ row }">
            {{ row.needCheck == 0 ? '不需要' : '需要' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['primary:gymRefundRule:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['primary:gymRefundRule:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改退票规则对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="550px" append-to-body>
      <el-form ref="gymRefundRuleFormRef" :model="form" :rules="rules" label-width="110px">
        <!--        <el-form-item label="健身房id" prop="gymId">
          <el-input v-model="form.gymId" placeholder="请输入健身房id" />
        </el-form-item> -->
        <el-form-item label="退票规则名称" prop="refundRuleName">
          <el-input v-model="form.refundRuleName" placeholder="请输入退票规则名称" @input="trimInput('refundRuleName')"/>
        </el-form-item>
        <el-form-item label="退款类型" prop="refundType">
          <!-- <span>{{form.refundType}}</span> -->
          <el-radio-group v-model="form.refundType">
            <el-radio v-for="istype in dataoo.refundType" :key="istype.value" :label="istype.value">
              {{ istype.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>



        <el-form-item label="允许过期退款" prop="allowExpiredRefund">
          <el-radio-group v-model="form.allowExpiredRefund">
            <el-radio v-for="istype in dataoo.options" :key="istype.value" :label="istype.value">
              {{ istype.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手续费类型" prop="refundFeeMode">
          <!-- 1-无手续费；2-每张票需要手续费；3-按销售价格百分比收取 -->
          <el-radio-group v-model="form.refundFeeMode">
            <el-radio v-for="istype in dataoo.refundFeeMode" :key="istype.value" :label="istype.value">
              {{ istype.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退款手续费" prop="refundFee">
          <!-- 当refundFeeMode=1时,refundFee=0；当refundFeeMode=2时,refundFee单位为元；当refundFeeMode=3时,refundFee单位是百分之一。比如退款手续费占销售价格的12% -->
          <el-input v-model="form.refundFee" placeholder="请输入退款手续费" @input="trimInput('refundFee')"/>
        </el-form-item>
        <el-form-item label="是否退款审核" prop="needCheck">
          <el-radio-group v-model="form.needCheck">
            <el-radio v-for="istype in dataoo.needCheck" :key="istype.value" :label="istype.value">
              {{ istype.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GymRefundRule" lang="ts">
  import { listGymRefundRule, getGymRefundRule, delGymRefundRule, addGymRefundRule, updateGymRefundRule } from '@/api/primary/gymRefundRule';
  import { GymRefundRuleVO, GymRefundRuleQuery, GymRefundRuleForm } from '@/api/primary/gymRefundRule/types';
  import { nextTick } from 'vue';
  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  const { g_refund_type, g_refundfee_type } = toRefs<any>(proxy?.useDict("g_refund_type", 'g_refundfee_type'));
  const gymRefundRuleList = ref<GymRefundRuleVO[]>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const idsname = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const queryFormRef = ref<ElFormInstance>();
  const gymRefundRuleFormRef = ref<ElFormInstance>();


  const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });
  const dataoo = reactive({
    options: [ //
      { value: 0, label: '不允许' },
      { value: 1, label: '允许' },
    ],
    refundType: [ //
      { value: 1, label: '不可退' },
      { value: 2, label: '有条件退(手续费限制、只能整单退等)' },
    ],
    refundFeeMode: [ //
      { value: 1, label: '无手续费(输入0)' },
      { value: 2, label: '每张票需要手续费(单位元)' },
      { value: 3, label: '按销售价格百分比收取(单位百分比%)' },
    ],
    needCheck: [ //
      { value: 0, label: '不需要' },
      { value: 1, label: '需要' },
    ],
  })
  const initFormData : GymRefundRuleForm = {
    id: undefined,
    gymId: undefined,
    refundRuleName: undefined,
    refundType: undefined,
    allowExpiredRefund: undefined,
    refundFeeMode: undefined,
    refundFee: undefined,
    needCheck: undefined,
  }
  const data = reactive<PageData<GymRefundRuleForm, GymRefundRuleQuery>>({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      gymId: undefined,
      refundRuleName: undefined,
      refundType: undefined,
      allowExpiredRefund: undefined,
      refundFeeMode: undefined,
      refundFee: undefined,
      needCheck: undefined,
      params: {
      }
    },
    rules: {
      id: [
        { required: true, message: "id不能为空", trigger: "change" }
      ],
      gymId: [
        { required: true, message: "健身房id不能为空", trigger: "change" }
      ],
      refundRuleName: [
        { required: true, message: "退票规则名称不能为空", trigger: "change" }
      ],
      refundType: [
        { required: true, message: "请选择退款类型", trigger: "change" }
      ],
      allowExpiredRefund: [
        { required: true, message: "允许过期退款；0-不允许；1-允许不能为空", trigger: "change" }
      ],
      refundFeeMode: [
        { required: true, message: "1-无手续费；2-每张票需要手续费；3-按销售价格百分比收取", trigger: "change" }
      ],
      refundFee: [
        { required: true, message: "请输入退款手续费", trigger: "change" }
      ],
      needCheck: [
        { required: true, message: "是否需要退款审核；0-不需要；1-需要，默认0不能为空", trigger: "change" }
      ],
    }
  });

  const { queryParams, form, rules } = toRefs(data);

  /** 查询退票规则列表 */
  const getList = async () => {
    loading.value = true;
    const res = await listGymRefundRule(queryParams.value);
    gymRefundRuleList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  }

  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  }

  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    gymRefundRuleFormRef.value?.resetFields();
  }
  const trimInput = (field) => {
    nextTick(() => {
      if (form.value[field]) {
        form.value[field] = form.value[field].trim();
      }
    });
  };
  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }

  /** 多选框选中数据 */
  const handleSelectionChange = (selection : GymRefundRuleVO[]) => {
    ids.value = selection.map(item => item.id);
    idsname.value = selection.map(item => item.refundRuleName);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加退票规则";
  }
  /** 修改按钮操作 */
  const handleUpdate = async (row ?: GymRefundRuleVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getGymRefundRule(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改退票规则";
  }

  /** 提交按钮 */
  const submitForm = () => {
    gymRefundRuleFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.id) {
          await updateGymRefundRule(form.value).finally(() => buttonLoading.value = false);
          proxy?.$modal.msgSuccess("修改成功");
        } else {
          await addGymRefundRule(form.value).finally(() => buttonLoading.value = false);
          proxy?.$modal.msgSuccess("添加成功");
          queryParams.value.refundRuleName = ''
          queryParams.value.allowExpiredRefund = ''
          queryParams.value.allowExpiredRefund = ''
        }

        dialog.visible = false;
        await getList();
      }
    });
  }

  /** 删除按钮操作 */
  const handleDelete = async (row ?: GymRefundRuleVO) => {
    const _ids = row?.id || ids.value;
    const name = row?.refundRuleName || idsname.value;
    await proxy?.$modal.confirm('是否确认删除退票规则为"' + name + '"的数据项？').finally(() => loading.value = false);
    await delGymRefundRule(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  }

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('primary/gymRefundRule/export', {
      ...queryParams.value
    }, `gymRefundRule_${new Date().getTime()}.xlsx`)
  }

  onMounted(() => {
    getList();
  });
</script>
